package org.quartz.impl.rmi;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.Properties;
import java.util.logging.Logger;

/**
 * Created by ziqiji on 2018/1/14.
 * 数据库连接池
 */
public class JDBCPool implements DataSource{

    //存放数据库连接
    private static LinkedList<Connection> listConnections = new LinkedList<>();

    //获取配置文件信息，创建数据库连接
    static {
        InputStream in = JDBCPool.class.getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        try {
            properties.load(in);
            String driver = properties.getProperty("driver");
            String url = properties.getProperty("url");
            String username = properties.getProperty("username");
            String password = properties.getProperty("password");

            //创建数据库连接池
            int jdbcPoolInitSize = Integer.parseInt(properties.getProperty("jdbcPoolInitSize"));
            Class.forName(driver);
            for (int i = 0 ; i < jdbcPoolInitSize ; i++){
                Connection connection = DriverManager.getConnection(url,username,password);
                connection.setAutoCommit(false);
                listConnections.add(connection);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }

    /**
     * description 获取数据库连接
     * @return 数据库连接
     * @throws SQLException SQL语句错误
     */
    @Override
    public Connection getConnection() throws SQLException{
        if (listConnections.size() > 0){
            final Connection conn = listConnections.removeFirst();
            System.out.println("...........size:"+listConnections.size());
            //返回Connection的代理对象
            return (Connection) Proxy.newProxyInstance(JDBCPool.class.getClassLoader(),
                    conn.getClass().getInterfaces(), new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            if (!method.getName().equals("close")){
                                return method.invoke(conn,args);
                            }else {
                                //调用是Connection对象的close方法，就把conn还给数据库连接池
                                listConnections.add(conn);
                                System.out.println("...............size:"+listConnections.size());
                                return null;
                            }
                        }
                    });
        }else {
            System.out.println("数据库忙");
            return null;
        }
    }
}
